Skip to content

K线 WS 推送 ​

连接地址:wss://stream.valuescan.ai/stream/ws/openapi/kline


一、概述 ​

K线 WS 推送用于持续接收指定代币的实时秒级 K线数据。客户端建立 WebSocket 连接并完成订阅后,将收到已订阅代币的 K线消息。

主要特性:

  • 实时推送:推送当前 K线实时变化,不仅限于已闭合 K线。
  • 秒级数据:当前仅推送 bucketType=1s 的秒级 K线。
  • 按连接订阅:每条 WS 连接独立维护订阅列表。
  • 断线重连:连接断开后,客户端需要重连并重新订阅。

说明:推送内容为实时行情变化,不承诺每个代币每秒都有消息。若需要 1m、5m、1h 等其他周期,请基于收到的秒级数据自行聚合。


二、连接地址 ​

GET wss://stream.valuescan.ai/stream/ws/openapi/kline

三、鉴权方式 ​

K线 WS 在建立连接时完成鉴权,鉴权参数放在 Query String 中。

参数类型必需说明
apiKeystring是ValueScan Access Key
signstring是HMAC-SHA256 签名
timestamplong是毫秒级 Unix 时间戳
noncestring是随机字符串(防重放)

签名算法:

sign = HMAC-SHA256(SK, timestamp毫秒 + nonce)

示例:

python
import hashlib
import hmac
import time
import uuid

AK = "your-access-key"
SK = "your-secret-key"

timestamp = str(int(time.time() * 1000))
nonce = uuid.uuid4().hex
sign = hmac.new(
    SK.encode(),
    (timestamp + nonce).encode(),
    hashlib.sha256,
).hexdigest()

四、点数消耗 ​

  • 计费方式:按用户收费,WS 连接期间,每 30 分钟收费 100 点数。
  • 额度不足处理:点数不足时,连接将收到标准错误消息并断开。

已成功扣费的 30 分钟计费周期内,连接可继续使用;下一计费周期点数不足时连接会断开。


五、连接与消息格式 ​

1. 连接成功 ​

连接建立并通过鉴权后,会收到:

json
{
    "type": "connected",
    "payload": {
        "requestId": "7b8a0b7f9f4a4f2c91f9e1e48c36d5b2"
    }
}

2. 订阅 ​

客户端发送:

json
{
    "type": "subscribe",
    "payload": {
        "items": [
            {
                "vsTokenId": 1
            }
        ]
    }
}

订阅确认:

json
{
    "type": "subscribed",
    "payload": {
        "items": [
            {
                "vsTokenId": 1
            }
        ]
    }
}

3. 取消订阅 ​

取消指定代币:

json
{
    "type": "unsubscribe",
    "payload": {
        "items": [
            {
                "vsTokenId": 1
            }
        ]
    }
}

取消当前连接的全部订阅:

json
{
    "type": "unsubscribe",
    "payload": {}
}

取消订阅确认:

json
{
    "type": "unsubscribed",
    "payload": {
        "items": []
    }
}

4. K线推送 ​

K线消息:

json
{
    "type": "data",
    "payload": {
        "vsTokenId": 1,
        "bucketType": "1s",
        "tradePair": "BTCUSDT",
        "klineType": "01",
        "time": 1781686187000,
        "open": 64873.11,
        "close": 64877.29,
        "high": 64877.3,
        "low": 64873.11,
        "volume": 0.27783,
        "value": 18023.8032114,
        "uniqueId": "01:BTCUSDT:1781686187000:1s"
    }
}

payload 字段说明:

字段类型说明
vsTokenIdlong代币 ID
bucketTypestringK线时间窗口,固定为 1s
tradePairstring默认 USDT 交易对
klineTypestringK线来源类型,详见 KlineType 枚举
timelongK线时间,毫秒时间戳
opennumber开盘价
closenumber收盘价
highnumber最高价
lownumber最低价
volumenumber成交量
valuenumber成交额
uniqueIdstring推送唯一标识,可用于客户端去重

六、订阅限制 ​

限制项上限说明
单用户 K线 WS 连接数50 条超过限制会返回限流错误
单条 WS 连接订阅代币数200 个 vsTokenId相同 vsTokenId 去重计数

建议客户端根据订阅规模进行分流:单连接订阅数量接近 200 时,拆分到新的连接中。


七、错误消息 ​

WS 建连后的业务错误使用统一 JSON 消息:

json
{
    "type": "error",
    "payload": {
        "code": 40001,
        "message": "Required parameter is missing",
        "requestId": "a7d7ce3053e140dca91d93df173648f8"
    }
}

常见错误码:

code说明
20001API Key 缺失
20012时间戳过期
20021签名验证失败
40001必填参数缺失,例如订阅项缺少 vsTokenId
40002参数格式或取值不合法
60001限流,例如连接数或订阅数超过上限
70001OpenApi 点数不足

建连阶段的鉴权错误会以 HTTP 200 返回业务 JSON,响应体中的 code 表示实际错误原因。


八、接入示例 ​

Python ​

依赖:

bash
pip install websocket-client

示例代码:

python
import hashlib
import hmac
import json
import time
import uuid
import urllib.parse
import websocket

AK = "your-access-key"
SK = "your-secret-key"
VS_TOKEN_ID = 1

timestamp = str(int(time.time() * 1000))
nonce = uuid.uuid4().hex
sign = hmac.new(
    SK.encode(),
    (timestamp + nonce).encode(),
    hashlib.sha256,
).hexdigest()

params = urllib.parse.urlencode({
    "apiKey": AK,
    "sign": sign,
    "timestamp": timestamp,
    "nonce": nonce,
})

url = f"wss://stream.valuescan.ai/stream/ws/openapi/kline?{params}"

ws = websocket.create_connection(url, timeout=10)

try:
    connected = json.loads(ws.recv())
    print("connected:", connected)

    ws.send(json.dumps({
        "type": "subscribe",
        "payload": {
            "items": [
                {"vsTokenId": VS_TOKEN_ID}
            ]
        }
    }))

    while True:
        message = json.loads(ws.recv())
        msg_type = message.get("type")

        if msg_type == "subscribed":
            print("subscribed:", message)
        elif msg_type == "data":
            kline = message["payload"]
            print(
                f"[{kline['tradePair']}] "
                f"time={kline['time']} close={kline['close']} volume={kline['volume']}"
            )
        elif msg_type == "error":
            print("error:", message)
            break
finally:
    ws.close()

九、断线重连建议 ​

K线 WS 连接可能因网络波动、服务维护或点数不足而断开。建议客户端:

  1. 监听连接关闭事件。
  2. 使用指数退避策略重连,避免短时间高频重试。
  3. 重连后重新生成 timestamp、nonce、sign。
  4. 重新发送订阅消息恢复订阅列表。
  5. 使用 uniqueId 对已处理的 K线消息做幂等去重。

示例重连间隔可设置为:1s、2s、4s、8s,最大不超过 60s。